package com.alander.nexusgo.im.controller;

import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.im.model.dto.CheckOnlineDTO;
import com.alander.nexusgo.im.model.dto.CreateTokenDTO;
import com.alander.nexusgo.im.model.dto.SendMsgDTO;
import com.alander.nexusgo.im.model.dto.MessageQueryDTO;
import com.alander.nexusgo.im.model.dto.ImMsgBody;
import com.alander.nexusgo.im.service.MessageService;
import com.alander.nexusgo.im.service.OnlineService;
import com.alander.nexusgo.im.service.TokenService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * IM服务接口控制器
 */
@RestController
@RequestMapping("/api/im")
public class ImController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private OnlineService onlineService;

    @Autowired
    private MessageService messageService;

    /**
     * 创建IM登录token
     *
     * @param createTokenDTO 创建token参数
     * @return token
     */
    @PostMapping("/token")
    public Result<String> createToken(@RequestBody CreateTokenDTO createTokenDTO) {
        try {
            String token = tokenService.createImLoginToken(createTokenDTO.getUserId(), createTokenDTO.getAppId());
            return Result.success(token);
        } catch (Exception e) {
            return Result.fail("创建token失败: " + e.getMessage());
        }
    }

    /**
     * 检查用户在线状态
     *
     * @param checkOnlineDTO 检查在线状态参数
     * @return 是否在线
     */
    @PostMapping("/online")
    public Result<Boolean> checkOnline(@RequestBody CheckOnlineDTO checkOnlineDTO) {
        try {
            boolean isOnline = onlineService.isOnline(checkOnlineDTO.getUserId(), checkOnlineDTO.getAppId());
            return Result.success(isOnline);
        } catch (Exception e) {
            return Result.fail("检查在线状态失败: " + e.getMessage());
        }
    }

    /**
     * 发送消息
     *
     * @param sendMsgDTO 发送消息参数
     * @return 是否发送成功
     */
    @PostMapping("/send")
    public Result<Boolean> sendMessage(@RequestBody SendMsgDTO sendMsgDTO) {
        try {
            ImMsgBody imMsgBody = new ImMsgBody();
            BeanUtils.copyProperties(sendMsgDTO, imMsgBody);
            
            boolean success = messageService.sendMsg(imMsgBody);
            return Result.success(success);
        } catch (Exception e) {
            return Result.fail("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 批量发送消息
     *
     * @param sendMsgDTOList 发送消息参数列表
     * @return 发送结果
     */
    @PostMapping("/batch-send")
    public Result<Map<String, Object>> batchSendMessage(@RequestBody java.util.List<SendMsgDTO> sendMsgDTOList) {
        try {
            java.util.List<ImMsgBody> imMsgBodyList = new java.util.ArrayList<>();
            for (SendMsgDTO sendMsgDTO : sendMsgDTOList) {
                ImMsgBody imMsgBody = new ImMsgBody();
                BeanUtils.copyProperties(sendMsgDTO, imMsgBody);
                imMsgBodyList.add(imMsgBody);
            }
            
            messageService.batchSendMsg(imMsgBodyList);
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", sendMsgDTOList.size());
            result.put("success", true);
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail("批量发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询消息历史记录
     *
     * @param queryDTO 查询参数
     * @return 消息列表
     */
    @PostMapping("/messages/history")
    public Result<Object> getMessageHistory(@RequestBody MessageQueryDTO queryDTO) {
        try {
            if (queryDTO.getAppId() == com.alander.nexusgo.im.constants.AppIdEnum.SINGLE_CHAT.getCode()) {
                // 单聊消息历史
                java.util.List<com.alander.nexusgo.im.model.entity.SingleMessage> messages = 
                    messageService.getMessagesBetweenUsers(queryDTO.getUserId(), queryDTO.getTargetUserId());
                return Result.success(messages);
            } else if (queryDTO.getAppId() == com.alander.nexusgo.im.constants.AppIdEnum.GROUP_CHAT.getCode()) {
                // 群聊消息历史
                java.util.List<com.alander.nexusgo.im.model.entity.GroupMessage> messages = 
                    messageService.getRecentGroupMessages(queryDTO.getGroupId(), queryDTO.getLimit());
                return Result.success(messages);
            }
            return Result.fail("不支持的应用类型");
        } catch (Exception e) {
            return Result.fail("查询消息历史失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     *
     * @param userId 用户ID
     * @param senderId 发送者ID
     * @return 是否成功
     */
    @PostMapping("/messages/read")
    public Result<Boolean> markMessagesAsRead(@RequestParam(value = "userId") Long userId, @RequestParam(value = "senderId") Long senderId) {
        try {
            int updated = messageService.markMessagesAsRead(userId, senderId);
            return Result.success(updated >= 0);
        } catch (Exception e) {
            return Result.fail("标记消息为已读失败: " + e.getMessage());
        }
    }
}